﻿using MS.Core.BaseProvider;
using MS.Core.Model;
using ReportDesignerServer.DataModel;
using ReportDesignerServer.DataModels;
using ReportDesignerServer.Dto;
using ReportDesignerServer.IRepository;
using SqlSugar;

namespace ReportDesignerServer.Services
{
    /// <summary>
    /// 通用字典服务
    /// </summary>
    public class UserService : ServiceBase<User, IUserRepository>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Repository"></param>
        public UserService(IUserRepository Repository)
        {
            this.Repository = Repository;
        }

        /// <summary>
        /// 获取角色字典
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<Role> GetRoleList()
        {
            return Repository.DB.Queryable<Role>().Where(c => c.status == 1).ToList();
        }

        /// <summary>
        /// 获取科室字典
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<Dept> GetDeptList()
        {
            return Repository.DB.Queryable<Dept>().Where(c => c.status == 1).ToList();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        public Rt SaveDeptInfo(Dept dept)
        {
            long res = 0;
            if (dept.id == 0)
            {
                res = Repository.DB.Insertable<Dept>(dept).ExecuteReturnSnowflakeId();
            }
            else
                res = Repository.DB.Updateable<Dept>(dept).ExecuteCommand();
            if (res > 0)
                return Rt.Success();
            else return Rt.Fail();
        }


        /// <summary>
        /// 获取通用字典
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public User GetLoginUser(string userName, string pwd)
        {
            Expressionable<User> expressionable = new Expressionable<User>();
            expressionable.And(c => c.username == userName);
            expressionable.And(c => c.password == pwd);
            return Repository.GetListByWhere(expressionable).FirstOrDefault();
        }

        /// <summary>
        /// 获取通用字典
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public User GetLoginUser(string id)
        {
            long userId = 0;
            if (long.TryParse(id, out userId))
            {
                return Repository.GetById(userId);
            }
            return null;
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserInfoVO GetUserInfo(string id)
        {
            long userId = 0;
            if (long.TryParse(id, out userId))
            {
                UserInfoVO info = Repository.DB.Queryable<User>().Where(c => c.id == userId).Select(c => new UserInfoVO()
                {
                    userId = c.id,
                    username = c.username,
                    nickname = c.nickname,
                    avatar = c.avatar
                }).First();
                if (info != null)
                {
                    //查角色
                    var roles = Repository.DB.Queryable<UserRole>()
                          .LeftJoin<Role>((ur, r) => ur.roleId == r.id)
                          .Where(ur => ur.userId == userId)
                          .Select((ur, r) => r.code).ToList();

                    //查权限
                    var perms = Repository.DB.Queryable<UserRole>()
                         .LeftJoin<RoleMenu>((ur, rm) => ur.roleId == rm.roleId)//多个条件用&&
                         .LeftJoin<Menu>((ur, rm, m) => rm.menuId == m.id)
                         .Where(ur => ur.userId == userId)
                         .Select((ur, rm, m) => m.perm)
                         .ToList().Where(c => c != null).ToList();
                    info.roles = roles;
                    info.perms = perms;
                    return info;
                }
            }
            return null;
        }


        /// <summary>
        /// 获取通用字典
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<User> GetUserList()
        {
            var res = Repository.DB.Queryable<User>()
                          .LeftJoin<Dept>((u, d) => u.deptId == d.id)
                          .Where((u, d) => u.username != "admin")
                          .Select((u, d) => new User() { deptName = d.name, password = "" }
                          , true).ToList();
            var roles = Repository.DB.Queryable<UserRole>().ToList();
            if (res != null)
            {
                res.ForEach(c =>
                {
                    c.roles = roles.FindAll(it => it.userId == c.id).Select(it => it.roleId.ToString()).ToList();
                });
            }
            return res;
        }

        /// <summary>
        /// 通过id获取用户信息
        /// </summary>
        /// <returns></returns>
        public User GetUserById(long userid)
        {
            var res = Repository.DB.Queryable<User>()
                          .Where((u) => u.id == userid)
                          .Select((u) => new User() { password = "" }
                          , true).First();
            if (res != null)
            {
                res.roles = Repository.DB.Queryable<UserRole>().Where(c => c.userId == userid).Select(it => it.roleId.ToString()).ToList();
            }
            return res;
        }
        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string ReSetUserPass(User user)
        {
            string newPass = new Random().Next(1000, 9999).ToString();
            user.password = newPass;
            int res = Repository.DB.Updateable(user).UpdateColumns(it => new { it.password, it.create_time }).ExecuteCommand();
            if (res > 0)
            {
                return newPass;
            }
            return null;
        }

        /// <summary>
        /// 保存一条用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Rt SaveUserInfo(User model)
        {
            long res = 0;
            if (model != null)
            {
                if (string.IsNullOrEmpty(model.username) || string.IsNullOrEmpty(model.nickname))
                {
                    return Rt.Fail("请填写登录名和用户名");
                }

                if (model.id == 0)
                {
                    //添加
                    int userCount = Repository.DB.Queryable<User>().Count(u => u.id == model.id);
                    if (userCount > 0)
                    {
                        return Rt.Fail("已存在相同工号的人员信息！");
                    }
                    Repository.DB.BeginTran();
                    model.status = 1;
                    model.password = "123";
                    try
                    {
                        long userid = Repository.DB.Insertable(model).ExecuteReturnSnowflakeId();
                        List<UserRole> userRoles = model.roles.Select(c => new UserRole() { userId = userid, roleId = long.Parse(c) }).ToList();
                        int urcount = Repository.DB.Insertable(userRoles).ExecuteCommand();
                        Repository.DB.CommitTran();
                    }
                    catch (Exception)
                    {
                        Repository.DB.RollbackTran();
                        return Rt.Fail("添加用户信息失败");
                    }
                }
                else
                {
                    Repository.DB.BeginTran();
                    try
                    {
                        Repository.DB.Deleteable<UserRole>().Where(c => c.userId == model.id).ExecuteCommand();
                        Repository.Update(model);

                        List<UserRole> userRoles = model.roles.Select(c => new UserRole() { userId = model.id, roleId = long.Parse(c) }).ToList();
                        int urcount = Repository.DB.Insertable(userRoles).ExecuteCommand();
                        res = 1;
                        Repository.DB.CommitTran();
                    }
                    catch (Exception)
                    {
                        Repository.DB.RollbackTran();
                        return Rt.Fail("更新用户信息失败");
                    }
                }
            }
            if (res > 0)
            {
                return Rt.Success();
            }
            else
            {
                return Rt.Error();
            }
        }

        /// <summary>
        /// 保存一条用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        public List<MenuVO> GetMenuRoute()
        {
            List<Menu> menus = Repository.DB.Queryable<Menu>().ToList();
            List<MenuVO> res = GetChild(menus, 0);
            return res;
        }
        /// <summary>
        /// 递归处理数据
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<MenuVO> GetChild(List<Menu> menus, long id)
        {
            List<Menu> finds = menus.FindAll(c => c.parentId == id);
            List<MenuVO> voList = new List<MenuVO>();
            if (finds?.Count > 0)
            {
                for (int i = 0; i < finds.Count; i++)
                {
                    Menu mu = finds[i];
                    MenuVO temp = new MenuVO() { path = mu.routePath, component = mu.component, name = mu.routePath, redirect = mu.redirect };
                    temp.meta = new MetaInfo() { title = mu.name, icon = mu.icon, hidden = mu.visible == 0, alwaysShow = mu.alwaysShow == 1, @params = mu.param, keepAlive = (mu.keepAlive == 1) };
                    temp.children = GetChild(menus, finds[i].id);
                    voList.Add(temp);
                }
                return voList;
            }
            return null;
        }
    }
}
